package com.insta.formation.calendar.manager.impl;

import com.insta.formation.calendar.dao.IPersonDao;
import com.insta.formation.calendar.manager.IUserManager;
import com.insta.formation.calendar.model.Person;

public class UserManagerImpl implements IUserManager
{

	private IPersonDao personDao;

	public UserManagerImpl(IPersonDao personDao) {
		this.personDao = personDao;
	}
	
	/**
	 * @see IUserManager.createUser()
	 */
	public boolean createUser(String email, String firstName, String lastName) {
		if (!existUser(email)) {
			Person person = new Person();
			person.setEmail(email);
			person.setFirstName(firstName);
			person.setLastName(lastName);
			if (validUser(person)) {
				Integer id = personDao.create(person);
				return (id != null);
			}
		}
		return false;
	}

	/**
	 * @see IUserManager.existUser()
	 */
	public boolean existUser(String email) {
		Person person = personDao.findByEmail(email);
		return ((person != null) ? true : false);
	}
	
	/**
	 * @see IUserManager.retreiveUser()
	 */
	public Person retreiveUser(String email) {
		return personDao.findByEmail(email);
	}
	
	/**
	 *	@see IUserManager.updateUser() 
	 */
	public boolean updateUser(Person person) {
		if ((validUser(person)) && (existUser(person.getEmail()))) {
			personDao.update(person);
			return true;
		}
		return false;
	}

	/**
	 * @see IUserManager.deleteUser()
	 */
	public boolean deleteUser(String email) {
		Person person = personDao.findByEmail(email);
		if (person != null) {
			personDao.delete(person);
			return true;
		}
		return false;
	}
	
	private boolean validUser(Person person) {
		return ((person.getEmail() != null) &&
				(person.getFirstName() != null) &&
				(person.getLastName() != null));
	}
}
